﻿package com.neriksworkshop.lib.tools 
{
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	/**
	* ...
	* @author www.neriksworkshop.com
	*/
	public class RandomTimer extends EventDispatcher
	{
		private var _t:Timer;
		private var _delay:Number;
		private var _repeatCount:int;
		private var _amplitude:Number;
		
		private var _currentCount:int;
		
		public function RandomTimer(_delay:Number, _repeatCount:int = 0, _amplitude:Number = .5) 
		{
			this._delay = _delay;
			this._repeatCount = _repeatCount;
			this._amplitude = _amplitude;
			
			
		}
		
		public function start():void
		{
			tick();
		}
		
		private function tick():void
		{
			if (_t)
			{
				_t.removeEventListener(TimerEvent.TIMER, onTimer);
				_t.stop();
				_t = null;
			}
			
			if (_currentCount >= _repeatCount && _repeatCount > 0) 
			{
				dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
				return;
			}
			
			_currentCount++;
			_t = new Timer(getRandomizedDelay(), 1);
			_t.addEventListener(TimerEvent.TIMER_COMPLETE, onTimer);
			_t.start();
		}
		
		private function onTimer(e:TimerEvent):void 
		{
			dispatchEvent(new TimerEvent(TimerEvent.TIMER));
			tick();
		}
		
		private function getRandomizedDelay():Number
		{
			var d:Number = _delay - (_amplitude * _delay) / 2 + Math.random()*(_amplitude * _delay);
			return d;
		}
		
	}
	
}